from datetime import datetime
from app import db


class UserShareRecord(db.Model):
    """用户分享记录模型"""
    __tablename__ = 'user_share_records'

    id = db.Column(db.Integer, primary_key=True)
    matchmaker_id = db.Column(db.Integer, db.ForeignKey('matchmakers.id', ondelete='CASCADE'), nullable=False, comment='红娘ID')
    user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False, comment='被分享用户ID')
    share_type = db.Column(db.String(20), default='manual', comment='分享类型：manual手动,auto自动')
    share_channel = db.Column(db.String(50), comment='分享渠道')
    share_content = db.Column(db.Text, comment='分享内容')
    click_count = db.Column(db.Integer, default=0, comment='点击次数')
    view_count = db.Column(db.Integer, default=0, comment='查看次数')
    conversion_count = db.Column(db.Integer, default=0, comment='转化次数')
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')

    # 索引
    __table_args__ = (
        db.Index('idx_matchmaker_id', 'matchmaker_id'),
        db.Index('idx_user_id', 'user_id'),
        db.Index('idx_created_at', 'created_at'),
    )

    def __repr__(self):
        return f'<UserShareRecord {self.id}>'

    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'matchmaker_id': self.matchmaker_id,
            'user_id': self.user_id,
            'share_type': self.share_type,
            'share_type_text': '手动分享' if self.share_type == 'manual' else '自动分享',
            'share_channel': self.share_channel,
            'share_content': self.share_content,
            'click_count': self.click_count,
            'view_count': self.view_count,
            'conversion_count': self.conversion_count,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None
        } 